#!/usr/bin/env python2.7
# -*- coding : utf-8 -*-

import sys
from Tkinter import *
from counter_const import *

class CheckBar(Frame):
    def __init__(self, parent=None, picks=[], side=LEFT, anchor=W):
        Frame.__init__(self, parent)
        self.vars = []
        for i in range(len(picks)):
            var = IntVar()
            chk = Checkbutton(self, text=picks[i], anchor=W,\
                              width=10, variable=var)
            chk.grid(row=(i // 4), column=(i % 4), sticky=W)
            self.vars.append(var)

    def state(self):
        return map((lambda var: var.get()), self.vars)

class RadioBar(Frame):
    def __init__(self, parent=None, picks=[], side=LEFT, anchor=W):
        Frame.__init__(self, parent)
        self.var = IntVar()
        for i in range(len(picks)):
            var = IntVar()
            chk = Radiobutton(self, text=picks[i], anchor=W, width=24, \
                              variable=self.var, value=(-1)**i)
            chk.grid(row=(i // 2), column=(i % 2), sticky=W)

    def state(self):
        return self.var.get()

class MainFrame():
    def __init__(self, frame_title=" MainFrame", parent=None):
        self.root = Tk(className=frame_title)
        self.root.resizable(False, False)
        self.counter_choice = 0
        self.feature_list = get_data(COUNTER_MSG_FEATURE)
        self.counter_list = get_data(COUNTER_MSG_INDIVIDUAL)
        self.operate_list = ['Activate', 'Deactivate']
        self.creat_bar()
        self.creat_button()
        self.root.protocol("WM_DELETE_WINDOW", self.cancel)
        self.root.mainloop()
        
    def creat_bar(self):
        self.feature_lab = Label(self.root, text="Feature")
        self.counter_lab = Label(self.root, text="Special Counter")
        self.operate_lab = Label(self.root, text="Operate")
        self.feature_bar = CheckBar(self.root, self.feature_list)
        self.counter_bar = CheckBar(self.root, self.counter_list)
        self.operate_bar = RadioBar(self.root, self.operate_list)
        self.feature_bar.config(relief=GROOVE, bd=2)
        self.counter_bar.config(relief=GROOVE, bd=2)
        self.operate_bar.config(relief=GROOVE, bd=2)
        self.feature_lab.pack(anchor=W, padx=6)
        self.feature_bar.pack(side=TOP, anchor=W, fill=X, padx=6)
        self.counter_lab.pack(anchor=W, padx=6)
        self.counter_bar.pack(side=TOP, anchor=W, fill=X, padx=6)
        self.operate_lab.pack(anchor=W, padx=6)
        self.operate_bar.pack(side=TOP, anchor=W, fill=X, padx=6)
        return None

    def creat_button(self):
        self.warning_lab = Label(self.root, text="", fg="red")
        self.warning_lab.pack(anchor=SW, padx=6, pady=6, side=LEFT)
        Button(self.root, text='Cancel', command=self.cancel, \
                       width=6).pack(side=RIGHT, pady=6, padx=28)
        Button(self.root, text='OK', command=self.ok_pressed, \
                       width=6).pack(side=RIGHT, pady=6)
        return None

    def check_counter(self):
        feature_checked = False
        for var in self.feature_bar.state():
            if var == 1:
                feature_checked = True
                break
        counter_checked = False
        for var in self.counter_bar.state():
            if var == 1:
                counter_checked = True
                break
        if feature_checked == counter_checked:
            if feature_checked:  # both choiced
                warning_str = "Choice one of Feature/Counter."
            else:  #none choiced
                warning_str = "No Feature/Counter choice."
            self.warning_lab.config(text=warning_str)
            self.feature_lab.config(fg="red")
            self.counter_lab.config(fg="red")
            return False
        else:
            self.feature_lab.config(fg="black")
            self.counter_lab.config(fg="black")
            if feature_checked:
                self.counter_choice = 1
            else:
                self.counter_choice = 2
            return True

    def check_operate(self):
        if self.operate_bar.state() == 0:
            warning_str = "Activate/Deactivate counters?"
            self.warning_lab.config(text=warning_str)
            self.operate_lab.config(fg="red")
            return False
        else:
            self.operate_lab.config(fg="black")
            return True

    def output_counter(self):
        print(COUNTER_MSG_TYPE)
        print(self.counter_choice)
        print(COUNTER_MSG_LIST)
        if self.counter_choice == 1:  # choice feature bar
            index_list = 0
            for var in self.feature_bar.state():
                if var == 1:
                    print(self.feature_list[index_list])
                index_list += 1
        elif self.counter_choice == 2:  # choice counter bar
            index_list = 0
            for var in self.counter_bar.state():
                if var == 1:
                    print(self.counter_list[index_list])
                index_list += 1
        return None

    def output_operate(self, operate):
        print(COUNTER_MSG_ACT)
        print(operate)
        return None

    def ok_pressed(self):
        if self.check_counter() and self.check_operate():
            self.output_operate(self.operate_bar.state())
            self.output_counter()
            self.root.destroy()
        return None

    def cancel(self):
        self.output_operate(0)
        self.root.destroy()
        return None

def get_data(stop_msg):
    data_list = []
    while True:
        line = sys.stdin.readline().strip()
        if line:
            if line == '':
                continue
            elif line == stop_msg:
                break
            else:
                data_list.append(line)
        else:
            break
    return data_list

if __name__ == '__main__':
    MainFrame(" RNC Counter MML")
